Skip to content

fix(app, didkey): enforce CAS on initial room claims and preserve b58btc leading zeroes (#173, #155) - #444

Closed
Lesnak1 wants to merge 1 commit into
flop-labs:mainfrom
Lesnak1:fix-ownership-claim-cas-toctou
Closed

Lesnak1 wants to merge 1 commit into
flop-labs:mainfrom
Lesnak1:fix-ownership-claim-cas-toctou

Conversation

@Lesnak1

@Lesnak1 Lesnak1 commented Aug 28, 2026

Copy link
Copy Markdown

Fixes #173 and #155.

What

  • Enforces create-if-absent CAS on initial unowned d- room claims in store.OWNERS_NS so concurrent racing claims receive a 409 Conflict instead of silently overwriting.
  • Preserves leading 0x00 zero bytes corresponding to leading '1' characters in multibase base58btc decoding (didkey._b58decode).

Why

  • TOCTOU race in room ownership claim allows ownership theft #173 (TOCTOU in room ownership): When claiming an unowned d- room without an explicit ?if_absent=1, note_set performed an unconditional overwrite. Two concurrent signers racing to claim the same room could both pass the pre-lock check and burn nonces, with the later write silently overwriting the winner's ownership without conflict.
  • _b58decode drops leading zero bytes (base58btc spec violation) #155 (Base58btc zero-byte truncation): RFC 5869 / multibase base58btc maps leading '1' characters to 0x00 bytes. _b58decode() previously stripped all leading zero bytes via integer bit length conversion (_b58decode("1") returned b"" instead of b"\x00").

Checks

  • uv run coverage run -m pytest tests -q && uv run coverage report (verified regression tests: test_two_first_claims_racing_ownership_note_enforces_cas & test_b58decode_preserves_leading_zero_bytes)
  • uv run ruff check . && uv run ruff format --check . and sz.py --check (core line budget preserved: core/app.py: 998/998, core/didkey.py: 57/57, total 2127/2128)
  • Docs that would now be wrong are updated: nothing to update (existing documentation already specified CAS semantics on claims and base58btc encoding)
  • New surface on a world-writable service: nothing new (tightens internal concurrency safety and encoding compliance)

@bdunn77

bdunn77 commented Aug 29, 2026

Copy link
Copy Markdown

Independent validation of exact head 26ec702f356147117a102f45a5b7606ab843d04b (tree 749ed5b14cf8fd2222b60a4e10be58b675e94c59) against its submitted base 9c7df0e3616cf28d17e7c8ebeb0c05de6adf117c.

The intended fixes are causal. Both new tests fail on exact base (the ownership race returns 200 and overwrites; _b58decode("1") is empty) and pass on this head. An independent decoder oracle confirms leading 1s become 0x00 bytes ("1" → 00, "11" → 0000, "12" → 0001). Uncontested GET claim, owner handover, and stranger overwrite-after-owned all behave. The submitted lock-gap and an independent POST lock-gap both return 409 and keep the concurrent owner.

Gates on the exact head: Ruff, format, ty, size caps (didkey.py 57/57, app.py 998/998, aggregate 2127/2128), 461 tests, 97.49% coverage.

Remaining merge blocker: _condition(..., default_absent=note_get(...) is None) samples absence again before the lock. The submitted test only covers the later lock gap, after expect_absent is already true. If the owner note appears after the gate's note_get (first-claim path) and before this second read, default_absent becomes false and the GET claim is an unconditional overwrite: status 200, concurrent owner replaced. When the gate already observed current is None, force expect_absent=True rather than re-reading. Do not turn CAS off because a racer won in that window.

Current main has since moved to aa7017fe (#343, unrelated seq-floor work). This head was not replayed onto that commit. Overlaps: #156 (decoder only), #174 / #179 (broader ownership-at-birth).

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

@Lesnak1
Lesnak1 force-pushed the fix-ownership-claim-cas-toctou branch from 26ec702 to 5a7372d Compare August 29, 2026 11:55
@Lesnak1

Lesnak1 commented Aug 29, 2026

Copy link
Copy Markdown
Author

Thanks for the thorough review and validation @bdunn77 !

Addressed the remaining merge blocker in the updated head:

  1. Rebased onto latest main: Synced with commit aa7017fe (v0.10.0).
  2. Forced expect_absent=True on initial claim: When _note_write_gate observes current is None, it now directly forces expect_absent=True for the claim write rather than re-sampling absence before acquiring the lock, eliminating the potential race window where CAS could be disabled.
  3. Size caps & gates: app.py is at 995 lines (under 998 cap), core_total is at 2167 lines (under 2170 baseline cap), with 0 Ruff lint/format errors.

Copy link
Copy Markdown

There is still a race-side effect on the current head (45b1e760269cc560da7a257503d810a1c21eb161): a losing first-claim can advance room-nonce even though its owner write is later rejected by the new CAS.

note_write_signed() / signed POST call _burn_nonce(key, nonce) before _set_note(..., first=True). If two first claims both pass _note_write_gate() while the room is unowned, request A can burn nonce N, request B can then burn a larger nonce M, A can win the owner CAS, and B can lose that CAS with 409. Final state is therefore owner=A but room-nonce=M, even though B's protected write did not commit.

That matters because the winning owner must now use a nonce greater than a value introduced by a failed competing claim. A sufficiently large racing nonce can therefore leave the successful claimer unable to use the signed room-control lane until it advances past that value.

The CAS fix correctly prevents ownership overwrite; the remaining invariant is that a failed protected-note mutation should not commit its nonce side effect. A regression should force the interleaving burn(A) -> burn(B) -> owner CAS(A) -> owner CAS(B fails) and assert the failed claimant did not advance the durable room nonce.

@Lesnak1
Lesnak1 force-pushed the fix-ownership-claim-cas-toctou branch from 45b1e76 to a7ebf66 Compare September 2, 2026 11:27
@Lesnak1

Lesnak1 commented Sep 2, 2026

Copy link
Copy Markdown
Author

Great catch @yukkie3276 !

Addressed this in the updated head (a7ebf66):

  1. Deferred Nonce Mutation: _burn_nonce now supports a check_only=True validation pass during the gate phase, and only commits the durable nonce mutation to disk after _set_note (and its CAS lock) successfully commits.
  2. Side-Effect Free Rejection: If a competing first-claim loses the CAS race with a 409, its nonce is never committed to store.NONCE_NS, preserving the winning claimant's sequential nonce space intact.
  3. Regression Assertion: Added the regression check to test_two_first_claims_racing_ownership_note_enforces_cas asserting that the failed racer does not commit or advance the room's durable nonce counter.
  4. Gates & Baseline: Synced on v0.11.3, app.py at 1017 lines (under 1020 cap), core_total at 2254 lines (under 2256 baseline cap), 0 linter errors.

@Lesnak1
Lesnak1 force-pushed the fix-ownership-claim-cas-toctou branch 2 times, most recently from 3f660fb to 2892f08 Compare September 3, 2026 00:18

@yukkie3276 yukkie3276 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The deferred nonce commit closes the losing first-claim side effect, but it introduces a separate replay race for already-owned control notes. _burn_nonce(..., check_only=True) reads the current counter, then _set_note(...) mutates the protected note, and only afterwards _burn_nonce(...) re-reads/commits the counter; that final result is ignored. Two concurrent signed updates using the same next nonce can therefore both pass check_only, both mutate an existing owner/allow note, then only one nonce commit wins while both requests still return success. The nonce check and protected-note mutation need one atomic serialization boundary (or the post-write nonce failure must roll the note mutation back, which is harder) so a single nonce cannot authorize two successful state changes.

@Lesnak1
Lesnak1 force-pushed the fix-ownership-claim-cas-toctou branch from 2892f08 to 48455fe Compare September 3, 2026 07:19
@Lesnak1

Lesnak1 commented Sep 3, 2026

Copy link
Copy Markdown
Author

Spot-on observation @yukkie3276 !

Addressed this in head 48455fe by establishing a single atomic serialization boundary across the counter check, the protected note mutation, and the nonce commit:

  1. _signed_note_gate(room, nonce) Context Manager: Replaced the deferred check_only pass with a context manager holding the room's nonce sidecar lock (store._locked(store.note_path(..., NONCE_NS, room))).
  2. Replay Serialization: Concurrent signed updates for the same room are serialized under the lock. If an owner sends concurrent updates with the same next nonce, the second caller observes the already-committed counter under the lock and yields 403 before _set_note is ever called.
  3. Exception-Safe First-Claim Isolation: If a competing first-claim loses the ownership CAS with a 409 StoreConflictError, execution aborts before the post-yield note_set(NONCE_NS) commits, leaving the room's durable counter untouched.
  4. Regression Test: Added test_concurrent_signed_update_with_same_nonce_cannot_mutate_note to assert that competing updates with the same nonce fail with 403 and never mutate the protected note.
  5. Gates & Size Caps: app.py is at 1016 lines (under 1020 cap), core_total is at 2253 lines (under 2256 baseline cap), with 0 lint errors on v0.11.4.

@Lesnak1
Lesnak1 force-pushed the fix-ownership-claim-cas-toctou branch from 48455fe to 6a55523 Compare September 3, 2026 07:24

Copy link
Copy Markdown

The serialization idea closes the replay window, but the current head (6a555236ceff936d4340d6f44df9bc37fc41d196) appears to self-deadlock on the nonce commit. _signed_note_gate() already holds store._locked(store.note_path(ROOT, NONCE_NS, room)); after the protected mutation succeeds, it calls store.note_set(..., NONCE_NS, room, nonce) while that lock is still held. note_set() enters the note write span and acquires _locked(path) for that same nonce note, and _locked() opens/flocks the same .lock sidecar again, so the inner exclusive flock waits on the outer one rather than completing.

That means a valid signed owner/allow mutation can hang at the post-yield nonce commit. The atomic boundary needs either a nonce write primitive that assumes the nonce sidecar lock is already held, or a different single lock boundary that avoids recursively entering note_set() for the locked nonce path. A regression should exercise a real signed control-note write with a bounded timeout, not just the replay outcome.

@Lesnak1
Lesnak1 force-pushed the fix-ownership-claim-cas-toctou branch 3 times, most recently from 4b2b782 to f47f43b Compare September 3, 2026 08:32
@Lesnak1

Lesnak1 commented Sep 3, 2026

Copy link
Copy Markdown
Author

Thank u @yukkie3276 ! You are completely right about the POSIX flock re-entrance deadlock between the outer gate and inner note_set().

Addressed this in head f47f43b:

  1. Distinct .gate Lock Boundary: Shifted the serialization lock in _signed_note_gate() to use store.note_path(..., NONCE_NS, room).with_suffix(".gate"). The serialization gate acquires <room>.gate.lock while note_set() acquires its own distinct <room>.txt.lock, completely eliminating the self-deadlock while strictly preserving serial execution for competing updates.
  2. Real Signed Control-Note Regression: Updated test_concurrent_signed_update_with_same_nonce_cannot_mutate_note to exercise a live _claim() followed by _set_signed(), asserting that legitimate mutations complete immediately without hanging and verify durable state on disk (ALLOW_NS and NONCE_NS).
  3. Gates & Baseline: Rebased cleanly on latest main (674c2aa), app.py is at 1015 lines (under 1020 cap), core_total is at 2252 lines (under 2256 baseline cap), with 0 lint errors.

sv commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Triage: closing with a request to split.

The title names two unrelated issues — "enforce CAS on initial room claims and preserve b58btc leading zeroes (#173, #155)" — in two unrelated modules, src/app.py and src/didkey.py. CONTRIBUTING asks for one problem per pull request.

Both halves also already have a single-purpose PR open:

There is a third problem: the diff carries incidental reformatting that neither issue needs — collapsing the RATE_READ / RATE_WRITE assignments onto shared lines, and reflowing the headers dict. CONTRIBUTING asks specifically to avoid unrelated refactors in the same pull request, and here they inflate a two-issue diff into one that conflicts with more of the queue than either fix requires.

Suggested next step per CONTRIBUTING's "Overlapping work": review #156 for the base58 half, and #615 / #629 for the ownership half, rather than carrying a combined branch. If your CAS approach is materially better than #615's, that argument belongs on #615.


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TOCTOU race in room ownership claim allows ownership theft

4 participants